package crm.model.studentPC;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import crm.model.Setting;
import crm.util.ErrorHandler;

public class ReceiveThread extends Thread{
	StudentPcService service;
	public ReceiveThread(StudentPcService service) {
		this.service = service;
	}



	public void run() {
		try {
			DatagramSocket udpSocket = new DatagramSocket(Setting.getSendPort());
			udpSocket.setBroadcast(true);
			byte[] buffer = new byte[0];
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			System.out.println("new Connection");
			udpSocket.receive(packet);
			System.out.println("it has received: ");
			InetAddress sendeAdresse = packet.getAddress();
			udpSocket.close();


			System.out.print(sendeAdresse);
            service.connect(sendeAdresse);


		} catch (SocketException e) {
			ErrorHandler.showAndWaitErrorMessage("Der Port " + Setting.getSendPort() + " ist belegt oder die Broadcastaddresse " + Setting.getBroadcastAddress() + " ist ungueltig");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
